"""
Here we provide a JSON-RPC interface to the logger.
"""

import math
import environment
from datetime import datetime

from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson

from lovely.jsonrpc import dispatcher
from lovely.jsonrpc.wsgi import WSGIJSONRPCApplication

from logger.api import Logger


class JSONLogger(Logger):

    def log(self, domain, context, msg_key=None, msg_value=None,
            timestamp=None, eventtype='info'):
        """Log a single message.

        Timestamp is taken as unix timestamp (float).
        """
        if timestamp is not None:
            timestamp = datetime.fromtimestamp(timestamp)
        return super(JSONLogger, self).log(domain, context,
                                           msg_key, msg_value,
                                           timestamp, eventtype)

    def batchLog(self, logs):
        """Log a list of log entries.

        The log entries must be provided as a dictionary.
        """
        result = []
        for l in logs:
            p = dict([(str(k), v) for k, v in l.iteritems()])
            result.append(self.log(**p))
        return result

    def query(self, filters=None, order=None, limit=10, offset=0, fields=None):
        result = super(JSONLogger, self).query(filters, order, limit, offset, fields)
        for d in result['data']:
            if 'timestamp' in d:
                dt = d['timestamp']
                timestamp = dt.strftime('%Y-%m-%d %H:%M:%S.')
                d['timestamp'] = timestamp + '%03d'% math.floor(dt.microsecond / 1000)
        return result

# create a JSON-RPC dispatcher for our Logger implementation.
loggerService = dispatcher.JSONRPCDispatcher(
                            JSONLogger(),
                            json_impl=simplejson,
                            )

application = WSGIJSONRPCApplication(
                    {'_jsonrpc/logger':loggerService,
                    })

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

